<template>
  <div class="database-result">
    <div class="result-header">
      <el-tag :type="result.success ? 'success' : 'danger'" size="small">
        {{ result.operation }} {{ result.success ? '成功' : '失败' }}
      </el-tag>
      
      <el-text size="small" type="info" v-if="result.executionTimeMs">
        耗时: {{ result.executionTimeMs }}ms
      </el-text>
    </div>

    <!-- 成功结果 -->
    <div v-if="result.success" class="result-content">
      <!-- 查询结果表格 -->
      <div v-if="result.data && result.data.length > 0" class="result-table">
        <el-table :data="result.data" style="width: 100%" size="small" stripe>
          <el-table-column
            v-for="(value, key) in result.data[0]"
            :key="key"
            :prop="key"
            :label="key"
            show-overflow-tooltip
            :width="getColumnWidth(key)"
          >
            <template #default="{ row }">
              <span v-if="typeof row[key] === 'boolean'">
                <el-tag :type="row[key] ? 'success' : 'info'" size="small">
                  {{ row[key] ? '是' : '否' }}
                </el-tag>
              </span>
              <span v-else-if="key === 'status'">
                <el-tag 
                  :type="getStatusType(row[key])" 
                  size="small"
                >
                  {{ formatStatus(row[key]) }}
                </el-tag>
              </span>
              <span v-else-if="key.includes('time') || key.includes('Time') || key.includes('At')">
                {{ formatDateTime(row[key]) }}
              </span>
              <span v-else>{{ formatValue(row[key]) }}</span>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="result-summary" v-if="result.data.length > 0">
          <el-text size="small" type="info">
            共 {{ result.data.length }} 条记录
            <span v-if="result.totalCount && result.totalCount > result.data.length">
              (总计 {{ result.totalCount }} 条)
            </span>
          </el-text>
        </div>
      </div>

      <!-- 无数据结果 -->
      <div v-else-if="result.operation === 'SELECT' || result.operation === 'COUNT'" class="no-data">
        <el-empty description="未找到符合条件的数据" :image-size="80" />
      </div>

      <!-- 操作结果 -->
      <div v-else class="operation-result">
        <el-result
          icon="success"
          :title="`${result.operation} 操作成功`"
          :sub-title="`影响了 ${result.affectedRows} 行数据`"
        />
      </div>

      <!-- SQL语句展示 -->
      <div v-if="result.executedSql" class="sql-display">
        <el-collapse>
          <el-collapse-item title="查看执行的SQL语句" name="sql">
            <el-input
              v-model="result.executedSql"
              type="textarea"
              :rows="3"
              readonly
              class="sql-textarea"
            />
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <!-- 失败结果 -->
    <div v-else class="error-result">
      <el-alert
        :title="`${result.operation} 操作失败`"
        type="error"
        :description="result.errorMessage"
        show-icon
        :closable="false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { DatabaseOperationResult } from '@/types'
import dayjs from 'dayjs'

interface Props {
  result: DatabaseOperationResult
}

const props = defineProps<Props>()

// 获取列宽度
function getColumnWidth(key: string): number | undefined {
  const shortColumns = ['id', 'age', 'status']
  const mediumColumns = ['username', 'email']
  
  if (shortColumns.includes(key)) return 80
  if (mediumColumns.includes(key)) return 150
  return undefined
}

// 获取状态类型
function getStatusType(status: string): string {
  switch (status?.toUpperCase()) {
    case 'ACTIVE': return 'success'
    case 'INACTIVE': return 'warning'
    case 'SUSPENDED': return 'danger'
    case 'SUCCESS': return 'success'
    case 'FAILED': return 'danger'
    default: return 'info'
  }
}

// 格式化状态
function formatStatus(status: string): string {
  const statusMap: Record<string, string> = {
    'ACTIVE': '活跃',
    'INACTIVE': '非活跃',
    'SUSPENDED': '暂停',
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PARTIAL_SUCCESS': '部分成功'
  }
  return statusMap[status?.toUpperCase()] || status
}

// 格式化日期时间
function formatDateTime(value: any): string {
  if (!value) return '-'
  
  try {
    const date = dayjs(value)
    if (date.isValid()) {
      return date.format('YYYY-MM-DD HH:mm:ss')
    }
  } catch (error) {
    // 忽略格式化错误
  }
  
  return String(value)
}

// 格式化值
function formatValue(value: any): string {
  if (value === null || value === undefined) return '-'
  if (typeof value === 'string' && value.trim() === '') return '-'
  return String(value)
}
</script>

<style scoped>
.database-result {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background: #fafafa;
}

.result-header {
  background: #f5f7fa;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-content {
  padding: 16px;
}

.result-table {
  margin-bottom: 16px;
}

.result-summary {
  text-align: right;
  padding: 8px 0;
  border-top: 1px solid #e4e7ed;
}

.no-data {
  text-align: center;
  padding: 20px;
}

.operation-result {
  text-align: center;
}

.error-result {
  padding: 16px;
}

.sql-display {
  margin-top: 16px;
}

.sql-textarea {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 12px;
}

.sql-textarea :deep(.el-textarea__inner) {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  color: #495057;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .result-content {
    padding: 12px;
  }
}
</style>